package com.enation.app.shop.front.policyInsurance.appController;

import com.enation.app.base.core.model.Member;
import com.enation.app.shop.component.gallery.model.GoodsGallery;
import com.enation.app.shop.component.gallery.service.impl.GoodsGalleryManager;
import com.enation.app.shop.core.goods.model.Goods;
import com.enation.app.shop.core.goods.model.GoodsParam;
import com.enation.app.shop.core.goods.model.Product;
import com.enation.app.shop.core.goods.model.support.ParamGroup;
import com.enation.app.shop.core.goods.service.GoodsTypeUtil;
import com.enation.app.shop.core.goods.service.IGoodsManager;
import com.enation.app.shop.core.goods.service.IProductManager;
import com.enation.app.shop.core.member.model.Favorite;
import com.enation.app.shop.core.member.service.IMemberManager;
import com.enation.app.shop.core.member.service.impl.FavoriteManager;
import com.enation.app.shop.core.member.service.impl.MemberCommentManager;
import com.enation.app.shop.core.order.model.Order;
import com.enation.app.shop.core.order.service.IOrderManager;
import com.enation.app.shop.front.api.commentagain.service.CommentAgainManager;
import com.enation.app.shop.front.api.commentlike.entity.CommentLike;
import com.enation.app.shop.front.api.commentlike.service.Impl.CommentLikeManager;
import com.enation.eop.sdk.utils.StaticResourcesUtil;
import com.enation.framework.action.JsonResult;
import com.enation.framework.util.JsonResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

@Scope("prototype")
@Controller
@RequestMapping("/app/policy")
public class InpolicyController {
    private static final Logger logger = LoggerFactory.getLogger(InpolicyController.class);
    @Autowired
    private IGoodsManager goodsManager;
    @Autowired
    private GoodsGalleryManager goodsGalleryManager;
    @Autowired
    private IProductManager productManager;
    @Autowired
    private IOrderManager orderManager;
    @Autowired
    private MemberCommentManager memberCommentManager;
    @Autowired
    private CommentAgainManager commentAgainManager;
    @Autowired
    private CommentLikeManager commentLikeManager;
    @Autowired
    private FavoriteManager favoriteManager;
    @Autowired
    private IMemberManager iMemberManager;

    /**
     * 政策性保险首页接口//more 为true表示点击更多
     *
     * @param userid
     * @return
     */
    @ResponseBody
    @RequestMapping("/index")
    public JsonResult getPolicy(Integer userid, Boolean more) {
        Member member = iMemberManager.getMemberAddress(userid);
        List<Goods> goodsList = goodsManager.getByType(70);//65：饲料  66：兽药  69：商业险  70：政策险
        List list = new ArrayList();
        Map map = new HashMap();
        boolean flag =false;
        for(int i=0;i<goodsList.size();i++){
            flag = member.getProvince_id()==goodsList.get(i).getProvince_id()
                    &&member.getCity_id()==goodsList.get(i).getCity_id();
//                    &&member.getRegion_id()==goodsList.get(i).getRegion_id();
            if(flag){
                    map.put("goodsid", goodsList.get(i).getGoods_id());
                    map.put("goodsname", goodsList.get(i).getName());
                    map.put("goodsprice", goodsList.get(i).getPrice());
                    map.put("buycount", goodsList.get(i).getBuy_count());
                    map.put("goodimg", StaticResourcesUtil.transformPathapp(goodsList.get(i).getThumbnail()));
//                    map.put("brief",goodsList.get(i).getBrief());
                    ParamGroup[] paramList = GoodsTypeUtil.converFormString(goodsList.get(i).getParams());
                    List<GoodsParam> goodsParams = null;
                    try {
                        for (int a = 0; a < paramList.length; a++) {
                            goodsParams = paramList[0].getParamList();
                        }
                        for (GoodsParam goodsParam : goodsParams) {
                            if (goodsParam.getName().equals("险种说明")) {
                                map.put("description", goodsParam.getValue());
                            }
                        }
                    } catch (Exception e) {
                        map.put("description", "");
                    }
                    list.add(map);
            }
            if (!more) {
                if (list.size() > 1) {
                    break;//默认推荐两个
                }
            }
        }
        return JsonResultUtil.getObjectMessageJson(list, "首页得到政策保险列表");
    }

    /**
     * 获取保险详情
     * @param goodsid
     * @return
     */
    @ResponseBody
    @RequestMapping("/getInPolicyDeatil")
        public  JsonResult  getinsurancebyid(Integer goodsid,Integer userid){
            List<Product> productList  = this.productManager.list(goodsid);
            Map detail=new HashMap();
            List<String> imgs=new ArrayList<String>();
            List<GoodsGallery> goodsGalleries=goodsGalleryManager.list(goodsid);
            for (GoodsGallery goodsGallery:goodsGalleries){
                imgs.add(StaticResourcesUtil.transformPathapp(goodsGallery.getThumbnail()));
            }
            Goods  goods =goodsManager.getGoods(goodsid);
            String goodname=goods.getName();
            detail.put("name",goodname);
            try {
                detail.put("thum",StaticResourcesUtil.transformPathapp(goods.getThumbnail()));
            }catch (Exception e){
                detail.put("thum", null);
            }
            detail.put("goodsid",goods.getGoods_id());
            detail.put("price",goods.getPrice());//销售价格
            detail.put("maprice",goods.getMktprice());//市场价格
            detail.put("maxcost",goods.getCost());//最高保额
            detail.put("buycount",goods.getBuy_count());//
            detail.put("expresfee","包邮");//快递费
            try {
                String introl=goods.getIntro();
                String introltemp=introl.substring(13,91);
                detail.put("introl",introltemp);
            }catch (Exception e){
                detail.put("introl",null);
            }
            List<GoodsParam> list=null;
            Map goodsdetail=new HashMap();
            if (goods.getType_id()==70){
                ParamGroup[] paramList =GoodsTypeUtil.converFormString(goods.getParams());
                List<GoodsParam> goodsParams=null;
                try {
                    for (int i=0;i<paramList.length;i++){
                        goodsParams=paramList[0].getParamList();
                    }
                    for (GoodsParam goodsParam:goodsParams){
                        if (goodsParam.getName().equals("险种说明")){
                            detail.put("description",goodsParam.getValue());
                        }
                    }
                }catch (Exception e){
                    detail.put("description","");
//                detail.put("helped","");
                    this.logger.error("数组下标越界",e);
                }
                if (goods.getType_id()==70){
                    detail.put("producttype",4);//政策险
                }
                    this.logger.error("数组下标越界");
            }
            List<Map<String,Object>>  colist= memberCommentManager.getGoodsComments(goodsid,1);
            Map<String,Object>  map11=null;
            Map comment=new HashMap();
            try{
                for (int i=0;i<colist.size();i++){
                    map11=colist.get(0);
                }
                if (map11==null){
                    comment=null;
                }else {
                    comment.put("commentid",map11.get("comment_id"));
                    comment.put("uname",map11.get("uname"));
                    String grade=map11.get("grade").toString();
                    try {
                        comment.put("commentstar",map11.get("star"));
                    }catch (Exception e){
                        comment.put("commentstar",2);
                    }
                    int uid=Integer.valueOf(map11.get("member_id").toString());
                    List<Order> order=orderManager.getByUserIdAndStatus(uid,null);
                    try {
                        for (Order order1:order){
//                        List<OrderItem> itemList =orderManager.listGoodsItems(order1.getOrder_id());
//                        for (OrderItem orderItem:itemList){
//                            if (goodsid==orderItem.getGoods_id()){
//                            }
//                        }
                            Long buytime=order1.getOrdertime();
                            comment.put("buytime",buytime);
                        }
                    }catch (Exception e){

                    }
                    try {
                        comment.put("face",StaticResourcesUtil.transformPathapp(map11.get("face").toString()));
                    }catch (Exception e){
                        comment.put("face",null);
                    }
                    Long i=Long.valueOf(map11.get("dateline").toString());
                    comment.put("commentdate",i*1000);
                    comment.put("content",map11.get("content"));
                    Integer commentid=Integer.parseInt(map11.get("comment_id").toString());
                    List<Map<String, Object>> imglist=memberCommentManager.getCommentGalleryImg(commentid);
                    List<String> commentimg=new ArrayList<String>();
                    if (imglist==null){
                        comment.put("img",new ArrayList<String>());
                    }else {
                        for (Map<String,Object> map:imglist){
                            String value=map.get("original").toString();
                            commentimg.add(StaticResourcesUtil.transformPathapp(value));
                        }
                        comment.put("img",commentimg);
                    }
                    comment.put("goodsname",goodname);
                    Integer commentagain= commentAgainManager.getCount(commentid);
                    Integer like= commentLikeManager.count(commentid);
                    comment.put("like",like);
                    comment.put("commentagain",commentagain);
                    CommentLike commentLike=commentLikeManager.getByUseridAndCommentId(userid,commentid,goodsid);
                    if (commentLike==null){
                        comment.put("thisuserlike",false);
                    }else {
                        if (commentLike.getStatus()==2){
                            comment.put("thisuserlike",false);
                        }else {
                            comment.put("thisuserlike",true);
                        }
                    }
                }
            }catch (Exception e){
                this.logger.error("数组下标越界",e);
            }
            List<Product> productList1  = this.productManager.list(goodsid);
            List<Map<String,Object>> pdetail=new ArrayList<Map<String, Object>>();
            for (Product product:productList1) {
                Map map2 = new LinkedHashMap();
                map2.put("pid", product.getProduct_id());
                map2.put("price", product.getPrice());
                //map2.put("productSn", product.getSn());
                map2.put("spec", product.getSpecs());
                pdetail.add(map2);
            }
            Favorite favorite=favoriteManager.get(goodsid,userid);
            if (favorite==null){
                goodsdetail.put("collect",0);
            }else {
                goodsdetail.put("collect",1);
            }
            int commentcount= memberCommentManager.getCommentsCount(goodsid);
            goodsdetail.put("imgs",imgs);
            goodsdetail.put("detail",detail);
            goodsdetail.put("specs",pdetail);
            goodsdetail.put("comment",comment);
            goodsdetail.put("commentcount",commentcount);
            return  JsonResultUtil.getObjectMessageJson(goodsdetail,"通过保险id得到保险");
    }

    /**
     * 获得保险方案信息
     * @param goodsid
     * @return
     */
    @ResponseBody
    @RequestMapping("/getInPolicyprogram")
    public JsonResult getInPolicyprogram(Integer goodsid) {
        if(goodsid==null){
            return JsonResultUtil.getErrorJson("缺少参数");
        }
        Goods goods = goodsManager.getGoods(goodsid);
        Map goodsMap = new HashMap();
        if (goods != null) {
            goodsMap.put("insurance_accountfor",goods.getInsurance_accountfor());
            goodsMap.put("stipulation_url",goods.getStipulation_url());
            goodsMap.put("stipulation",goods.getStipulation());
            goodsMap.put("unit_price", goods.getPrice());
            goodsMap.put("insured_subsidies", goods.getInsured_subsidies());
            goodsMap.put("central_subsidies", goods.getCentral_subsidies());
            goodsMap.put("province_subsidies", goods.getProvince_subsidies());
            goodsMap.put("city_subsidies", goods.getCity_subsidies());
            goodsMap.put("region_subsidies",goods.getRegion_subsidies());
            goodsMap.put("farmer_subsidies",goods.getFarmer_subsidies());
            goodsMap.put("other_subsidies", goods.getOther_subsidies());
            goodsMap.put("item",goods.getItem());
            goodsMap.put("unit",goods.getUnit());
        } else {
            return JsonResultUtil.getErrorJson("获取信息失败!");
        }
        return JsonResultUtil.getObjectMessageJson(goodsMap, "获取数据成功!");
    }
}